<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>40.JSON序列化与自定义toJSON</title>
</head>

<body>
  <script>
    //序列化是将 json 转换为字符串，一般用来向其他语言传输使用。

    let hd = {
      "title": "后盾人",
      "url": "houdunren.com",
      "teacher": {
        "name": "向军大叔",
      }
    }
    //{"title":"后盾人","url":"houdunren.com","teacher":{"name":"向军大叔"}}
    console.log(JSON.stringify(hd));

    //根据第二个参数指定保存的属性
    //{"title":"后盾人","url":"houdunren.com"}
    console.log(JSON.stringify(hd, ['title', 'url']));

    // 为数据添加 toJSON 方法来自定义返回格式

    let hd2 = {
      "title": "后盾人",
      "url": "houdunren.com",
      "teacher": {
        "name": "向军大叔",
      },
      "toJSON": function () {
        return {
          "title": this.url,
          "name": this.teacher.name
        };
      }
    }
    //{"title":"houdunren.com","name":"向军大叔"}
    console.log(JSON.stringify(hd2));
  </script>
</body>

</html>